package com.lovi.io_;

import org.junit.jupiter.api.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * 文件输入流
 */
public class FileInputStream2_ {
    /**
     * 方法1，单字符读取
     * 原始：hello我的宝贝呀~
     * 得到：helloæçå®è´å~
     */
    @Test
    public void readFile01() throws IOException {
        int readData = 0;
        String filePath = "e:\\news2.txt";
        File file = new File(filePath);
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
            //开始读取
            while ((readData = fileInputStream.read())!=-1){
                System.out.print((char) readData);
            }
        } catch (RuntimeException e) {
            throw new RuntimeException(e);
        }finally {
            fileInputStream.close();
        }

    }

    /**
     * 一次读8个字节
     * @throws IOException
     * 原始：hello我的宝贝呀~
     * 读到的：hello我的宝��呀~
     */
    @Test
    public void readFile02() throws IOException {

        int readLen = 0;//每次读取到的字节数
        byte[] bytes = new byte[8];
        String filePath = "e:\\news2.txt";
        File file = new File(filePath);
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
            //开始读取
            while ((readLen = fileInputStream.read(bytes))!=-1){
                System.out.print(new String(bytes,0,readLen));
            }
        } catch (RuntimeException e) {
            throw new RuntimeException(e);
        }finally {
            fileInputStream.close();
        }
    }
}

